package com.valten.service.impl;

import com.valten.pojo.Article;
import com.valten.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

@Service("articleService")
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Article article) {
        mongoTemplate.save(article);
    }

    @Override
    public void batchSave(List<Article> articles) {
        mongoTemplate.insertAll(articles);
    }

    @Override
    public void update(Article article) {
        //创建更新条件
        Query query = new Query();
        Criteria criteria = Criteria.where("id").is(article.getId());
        query.addCriteria(criteria);

        //创建更新对象
        Update update = new Update();
        update.set("title", article.getTitle());
        update.set("content", article.getContent());
        update.set("stars", article.getStars());
        update.set("publicDate", new Date());

        //更新所有符合条件的记录
        mongoTemplate.updateMulti(query, update, Article.class);
    }

    @Override
    public void deleteById(Long id) {
        //创建删除条件
        Query query = new Query();
        Criteria criteria = Criteria.where("id").is(id);
        query.addCriteria(criteria);
        mongoTemplate.remove(query, Article.class);
    }

    @Override
    public Article findById(Long id) {
        Query query = new Query();
        Criteria criteria = Criteria.where("id").is(id);
        query.addCriteria(criteria);
        return mongoTemplate.findOne(query, Article.class);
    }

    @Override
    public List<Article> findAll() {
        return mongoTemplate.findAll(Article.class);
    }

    @Override
    public List<Article> findByTitle(String title) {
        Query query = new Query();
        //模糊查询，不区分大小写
        Pattern pattern = Pattern.compile("^.*" + title + ".*$", Pattern.CASE_INSENSITIVE);
        Criteria criteria = Criteria.where("title").regex(pattern);
        query.addCriteria(criteria);
        return mongoTemplate.find(query, Article.class);
    }
}